// pages/borrowapply_public/borrowapply_public.js
var dateTimePicker = require('../../utils/detai.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pagenumber:0,  // 指示点下标
    swiperItem:[], // 轮播图数组
    id:'',

    stesinaems:'',//当前年月日
    userinfo:{},//用户信息接口
    getBookInfoList:{},  
    startdate: '请选择起借日期',//开始时间
    enddate: '请选择还书日期' ,//结束时间

    yanqistartdate: '请选择新的还书时间',//申请延期时间

    dates: '2018-10-01',
    time: '12:00',
    dateTimeArray: null,
    dateTime: null,
    dateTimeArray1: null,
    dateTime1: null,
    startYear: 2000,
    endYear: 2050,
  },

  // 点赞
  myPraisess:function(){
    var that = this;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: getApp().url.dev + '/api/book/bookGiveLike/'+that.data.getBookInfoList.book.id, //这里就写上后台解析手机号的接口
      //这里的几个参数是获取授权后的加密数据，作为参数传递给后台就行了
      data: {},
      method: 'get',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
         'token': wx.getStorageSync("token"),
      },
      success(res) {
        wx.hideLoading()
        if(res.data.code == 200){
          that.getBookInfo(); //书籍详情
        }
      }
    })
  },

  // 轮播图方法
  swiperChange: function(e) {
    this.setData({
      pagenumber: e.detail.current
    })
  },
  // 书页方法
  pagenumbersdff(res) {
    this.setData({
      pagenumber: res.currentTarget.dataset.index,
      swiperindex: res.currentTarget.dataset.index,
    })
  },


  // 免押金
  mianyejin:function(){
    var that = this;
    console.log(this.data.getBookInfoList);
    if(this.data.startdate == '请选择起借日期'){
      wx.showToast({ title: '请选择正确的时间',  icon:'none' })
      return;
    }
    if(this.data.enddate == '请选择还书日期'){
      wx.showToast({ title: '请选择还书日期',  icon:'none' })
      return;
    }
    wx.showModal({
      title: '提示',
      content: '是否提交申请',
      success (res) {
        if (res.confirm) {
          that.addOrdersFree()
        } else if (res.cancel) {
        }
      }
    })
  },

  // 借书申请-免押金支付
  addOrdersFree:function(){
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    wx.request({
      url: getApp().url.dev + '/api/orders/addOrdersFree', //这里就写上后台解析手机号的接口
      //这里的几个参数是获取授权后的加密数据，作为参数传递给后台就行了
      data: {
        beginTime:that.data.startdate,//借书开始时间
        bookId:that.data.getBookInfoList.book.id,//书籍id
        endTime:that.data.enddate,//借书结束时间
      },
      method: 'get',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'token': wx.getStorageSync("token"),
      },
      success(res) {
        wx.hideLoading()
        if (res.data.code == 200) {
          wx.showToast({ title: res.data.msg,  icon:'none' })
          setTimeout(()=>{
            var pages = getCurrentPages()
            var beforePage = pages[pages.length - 2];
            beforePage.getBookInfo();
            wx.navigateBack({
              delta: 1
            })
          },1000)
        }else{
          wx.showToast({ title: res.data.msg,  icon:'none' })
        }
      }
    })
  },


  // 押金支付
  yuepay:function(){
    var that = this;
    console.log(this.data.getBookInfoList);
    if(this.data.startdate == '请选择起借日期'){
      wx.showToast({ title: '请选择正确的时间',  icon:'none' })
      return;
    }
    if(this.data.enddate == '请选择还书日期'){
      wx.showToast({ title: '请选择还书日期',  icon:'none' })
      return;
    }
    wx.showModal({
      title: '提示',
      content: '是否提交申请',
      success (res) {
        if (res.confirm) {
          that.addOrdersByWxPay()
        } else if (res.cancel) {
        }
      }
    })
  },

  // 押金支付方法
  addOrdersByWxPay:function(){
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    wx.request({
      url: getApp().url.dev + '/api/orders/addOrdersByWxPay', //这里就写上后台解析手机号的接口
      //这里的几个参数是获取授权后的加密数据，作为参数传递给后台就行了
      data: {
        beginTime:that.data.startdate,//借书开始时间
        bookId:that.data.getBookInfoList.book.id,//书籍id
        endTime:that.data.enddate,//借书结束时间
      },
      method: 'get',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'token': wx.getStorageSync("token"),
      },
      success(res) {
        console.log(res);
        wx.hideLoading()
        if (res.data.code == 200) {
          wx.showToast({ title: res.data.msg,  icon:'none' })
          wx.requestPayment(
            {
            'timeStamp':res.data.data.timeStamp,//时间戳
            'nonceStr': res.data.data.nonceStr,//随机字符串
            'package': res.data.data.packageValue,//统一下单接口返回的 prepay_id 参数值
            'signType': 'MD5',//签名类型，
            'paySign': res.data.data.paySign,//签名,
            'success':function(res){
                console.log(res)
                if(res.errMsg == 'requestPayment:ok'){
                  var that = this
                  // var pages = getCurrentPages()
                  // var beforePage = pages[pages.length - 2];
                  // beforePage.orderdetail()
                  wx.navigateBack({
                    delta: 1
                  })
                }else{
                }
            },
          })
        }else{
          wx.showToast({ title: res.data.msg,  icon:'none' })
        }
      }
    })
  },

  // 信用分支付
  xinyongpay:function(){
    var that = this;
    if(this.data.startdate == '请选择起借日期'){
      wx.showToast({ title: '请选择正确的时间',  icon:'none' })
      return;
    }
    if(this.data.enddate == '请选择还书日期'){
      wx.showToast({ title: '请选择还书日期',  icon:'none' })
      return;
    }
    wx.showModal({
      title: '提示',
      content: '是否提交申请',
      success (res) {
        if (res.confirm) {
          that.addOrdersIntegral()
        } else if (res.cancel) {
        }
      }
    })
  },
  
  // 借书申请-积分支付
  addOrdersIntegral:function(){
      wx.showLoading({
        title: '加载中',
      })
      var that = this;
      wx.request({
        url: getApp().url.dev + '/api/orders/addOrdersIntegral', //这里就写上后台解析手机号的接口
        //这里的几个参数是获取授权后的加密数据，作为参数传递给后台就行了
        data: {
          beginTime:that.data.startdate,//借书开始时间
          bookId:that.data.getBookInfoList.book.id,//书籍id
          endTime:that.data.enddate,//借书结束时间
        },
        method: 'get',
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'token': wx.getStorageSync("token"),
        },
        success(res) {
          console.log(res);
          wx.hideLoading()
          if (res.data.code == 200) {
            wx.showToast({ title: res.data.msg,  icon:'none' })
            setTimeout(()=>{
              var pages = getCurrentPages()
              var beforePage = pages[pages.length - 2];
              beforePage.getBookInfo();
              wx.navigateBack({
                delta: 1
              })
            },1000)
          }else{
            wx.showToast({ title: res.data.msg,  icon:'none' })
          }
        }
      })
    },


  // 开始时间选择事件
  startbindDateChange: function (e) {
    this.setData({
      startdate: e.detail.value
    })
    var start = (new Date((this.data.startdate.replace(/-/g, "/"))));
    var end = (new Date((this.data.enddate.replace(/-/g, "/"))));
    var days = parseInt((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
    if (days < 0) {
      wx.showToast({
        title: '请选择正确的时间',
        icon:'none'
      })
      this.setData({
        startdate: '请选择正确的时间',
      })
      this.totaldays();
    }
    this.totaldays();
  },
  // 结束时间选择事件
  endbindDateChange: function (e) {
    this.setData({
      enddate: e.detail.value
    })
    var start = (new Date((this.data.startdate.replace(/-/g, "/"))));
    var end = (new Date((this.data.enddate.replace(/-/g, "/"))));
    var days = parseInt((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));

    if (days < 0) {
      wx.showToast({
        title: '请选择正确的时间',
        icon:'none'
      })
      this.setData({
        enddate: '请选择还书日期'
      })
      this.totaldays();
    }
    this.totaldays();
  },
  // 差值天数事件
  totaldays() {
    var start = (new Date((this.data.startdate.replace(/-/g, "/"))));
    var end = (new Date((this.data.enddate.replace(/-/g, "/"))));
    var days = parseInt((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
    this.setData({
      totaldays: days
    })
  },
  // 页面加载事件
  onLoad: function (options) {
    this.setData({
      id:options.id,
    })
    this.getBookInfo(); //书籍详情
    this.undatatimer(); //获取当前年月日
    this.totaldays();
    this.getUserInfo(); //获取用户信息

    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    // 精确到分的处理，将数组的秒去掉
    var lastArray = obj1.dateTimeArray.pop();
    var lastTime = obj1.dateTime.pop();
    
    this.setData({
      dateTime: obj.dateTime,
      dateTimeArray: obj.dateTimeArray,
      dateTimeArray1: obj1.dateTimeArray,
      dateTime1: obj1.dateTime
    })
  },

// 书籍详情
getBookInfo: function() {
  wx.showNavigationBarLoading();
  var that = this;
  wx.request({
    url: getApp().url.dev + '/api/book/getBookInfo/' + that.data.id, //这里就写上后台解析手机号的接口
    //这里的几个参数是获取授权后的加密数据，作为参数传递给后台就行了
    data: {},
    method: 'get',
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'token': wx.getStorageSync("token"),
    },
    success(res) {
      console.log(res);
      if (res.data.code == 200) {
        //隐藏导航条加载动画
        wx.hideNavigationBarLoading();
        //停止下拉刷新
        wx.stopPullDownRefresh();
        that.setData({
          getBookInfoList: res.data,
          swiperItem:res.data.book.bookCover.split(','),
        })
        // that.zujuians();
      }
    }
  })
},





  changeDateTime1(e) {
    this.setData({ dateTime1: e.detail.value });
  },

  changeDateTimeColumn1(e) {
    var arr = this.data.dateTime1, dateArr = this.data.dateTimeArray1;

    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({ 
      dateTimeArray1: dateArr,
      dateTime1: arr
    });
  },

  // 获取当前年月日
  undatatimer:function(){
    var timestamp = Date.parse(new Date());
    var date = new Date(timestamp);
    //获取年份  
    var Y =date.getFullYear();
    //获取月份  
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //获取当日日期 
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(); 
    // console.log("当前时间：" + Y + '年'  + M+ '月' + D+ '日' );
    this.setData({
      stesinaems:Y +'-'+ M +'-'+ D
    })
  },


  // 获取用户信息
  getUserInfo:function(){
    var that = this;
    wx.request({
      url: getApp().url.dev + '/api/user/getUserInfo', //这里就写上后台解析手机号的接口
      //这里的几个参数是获取授权后的加密数据，作为参数传递给后台就行了
      data: {},
      method: 'get',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
         'token': wx.getStorageSync("token"),
      },
      success(res) {
        console.log(res);
        if(res.data.code == 200){
          that.setData({
            userinfo:res.data.data
          })
        }
      }
    })
  }, 




    // 请选择新的还书时间
    yanqistartbindDateChange: function (e) {
      this.setData({
        yanqistartdate: e.detail.value
      })
    },

    // 确认并提交
    querenundata:function(){
      this.setData({
        yanqistartdate:this.data.dateTimeArray1[0][this.data.dateTime1[0]]+'-'+this.data.dateTimeArray1[1][this.data.dateTime1[1]]+'-'+this.data.dateTimeArray1[2][this.data.dateTime1[2]]+' '+this.data.dateTimeArray1[3][this.data.dateTime1[3]]+':'+this.data.dateTimeArray1[4][this.data.dateTime1[4]]
      })
      console.log(this.data.yanqistartdate);
      var that = this;
      if(this.data.yanqistartdate == '请选择新的还书时间'){
        wx.showToast({ title: '请选择新的还书时间', icon:'none' })
        return;
      }
      wx.showModal({
        title: '提示',
        content: '是否申请延期归还',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            that.applyPostpone();
          } else if (res.cancel) {
            // console.log('用户点击取消')
          }
        }
      })
      
    },
    // 书籍延期申请 方法 
    applyPostpone:function(){
      wx.showNavigationBarLoading();
      var that = this;
      wx.request({
        url: getApp().url.dev + '/api/orders/applyPostpone', //这里就写上后台解析手机号的接口
        //这里的几个参数是获取授权后的加密数据，作为参数传递给后台就行了
        data: {
          applyDate:that.data.yanqistartdate,//申请截止日期
          ordersId:that.data.getBookInfoList.waitOrders.id,//订单id
        },
        method: 'get',
        header: {
          'content-type': 'application/x-www-form-urlencoded',
          'token': wx.getStorageSync("token"),
        },
        success(res) {
          //隐藏导航条加载动画
          wx.hideNavigationBarLoading();
          //停止下拉刷新
          wx.stopPullDownRefresh();
          console.log(res);
          if(res.data.code == 200){
            wx.showModal({
              title: '',
              content: res.data.msg,
              showCancel:false,
              success (res) {
                if (res.confirm) {
                  wx.navigateBack({
                    delta: 1
                  })
                } else if (res.cancel) {
                  // console.log('用户点击取消')
                }
              }
            })
            
          }else{
            wx.showToast({ title: res.data.msg, icon:'none' })
          }
        }
      })
    }

})